//author 李伟利
//@date 2023-5-26
//H5界面 属性面板创建
$.extend({ propComp: {} });
$.extend($.propComp, {
  BASE_GRID_ROW_NAME_0: "标签",
  BASE_GRID_ROW_NAME_1: "名称",
  BASE_GRID_ROW_NAME_2: "英文名称/地址",
  menuList: [
    { title: "视图菜单", layOptions: "{ id: 0 }" },
    { title: "基本属性", layOptions: "{ id: 1 }" },
    { title: "模型属性", layOptions: "{ id: 2 }" },
  ],
  //基本信息
  baseInfo: {
    tableData: [],
    tableCol: [
      { field: "name", title: "属性名" },
      { field: "value", title: "值" },
      { field: "visiable", title: "显示" },
    ],
  },
  //模型属性
  modelInfo: {
    tableData: [],
    tableCol: [
      { field: "name", title: "属性名" },
      { field: "value", title: "值" },
      { field: "unit", title: "单位" },
      { field: "memo", title: "备注" },
    ],
  },
  init() {
    console.log("experimentData", experimentData);
    this.table = layui.table;
    this.tree = layui.tree;
    this.initDrawConPage(); //初始化抽屉内容界面
    this.initMindMapPage(); //初始化视图菜单 抽屉内容
    this.initEvent(); //初始化事件
  },
  initEvent() {
    $("#menu-iconfont").click(() => {
      this.clear();
      this.showDrawerPage();
    });
  },
  //右侧菜单按钮 菜单属性点击触发
  menuPropClick() {
    this.clear();
    this.showDrawerPage();
  },
  //获取选中元器件的属性值
  getModelProp() {
    let context = window.app.getContext();
    console.log("[ context.activeEditorObj ] >", context.activeEditorObj);
    let expActiveJsonModel = context?.activeEditorObj?.model;
    return expActiveJsonModel?.property?.modelProperty;
    // let activeEditor = context.getActiveEditor();
    // let figures = activeEditor.canvas.getSelection().getAll();
    // let data = figures.data[0];
    // return data ? data.properties?.modelProperty : "";
  },
  initMindMapPage() {
    var dom = `<div id="tree-view"></div>`;
    $("body").append(dom);
  },
  initDrawConPage() {
    var that = this;
    var ulDom = `<ul class="layui-menu" id="drawer-content"></ul>`;
    var liDom = "";
    this.menuList.forEach((item) => {
      liDom += `<li lay-options="${item.layOptions}">
                  <div class="layui-menu-body-title">${item.title}</div>
                </li>`;
    });
    $("body").append(ulDom);
    $("#drawer-content").append(liDom);
    $("#drawer-content li").click(function () {
      let title = $(this).text().trim();
      if (title == "视图菜单") {
        that.showViewMenuDrawer();
        return;
      }
      if (!that.getModelProp()) {
        layer.msg("请选择元器件 / 没有属性内容");
        return;
      }
      if (title == "基本属性") {
        that.showPropDia("base");
      } else if (title == "模型属性") {
        that.showPropDia("model");
      }
    });
  },
  showViewMenuDrawer() {
    layer.open({
      type: 1,
      // r表示right,b表示bottom
      offset: "rt",
      // 标题
      title: "视图菜单",
      shadeClose: true, // 点击遮罩区域，关闭弹层
      // anim 特效 0-平滑放大 1-从上掉落 2-从底部往上滑入 3-从左滑入 4-从左翻转 5-渐显 6-抖动
      anim: 0,
      // 第一个参数宽度，第二个参数高度
      area: ["70%", "100%"],
      // 内容区 在body中写入<div id="draw">。。。。</div>代码，即弹窗内容
      content: $("#tree-view"),
    });
    //树结构的数据是对象的数组，确保格式正确
    this.renderTree();
  },
  renderTree() {
    var that = this;
    var treeData = experimentData.firstPage.treeData;
    //递归处理tree结构数据
    var setTreeField = function (data) {
      data.forEach((item) => {
        item.title = item.text;
        item["spread"] = true;
        item.children && setTreeField(item.children);
      });
    };
    setTreeField([treeData]);
    console.log("treeData", treeData);
    this.tree.render({
      elem: "#tree-view",
      data: [treeData],
      onlyIconControl: true,
      click: function (obj) {
        console.log("tree click", obj);
        that.treeRowClick(obj);
      },
    });
  },
  treeRowClick({ data }) {
    // let layid = $.tabComp.getTabSelectLayid();
    // $.loading.open();
    $.tabComp.tabChange("firstPage");
    window.selectTreeNode = data;
    this.selectPartlib(data);
    layer.closeAll(); //关闭所有的抽屉弹框
  },
  selectPartlib(node) {
    var context = app.context.activeEditor.rootEditPart.figure.context;
    var rootEditPart = context.getRootEditPart();
    // var rootModel = rootEditPart.getModel();
    //实验台所有器件
    var models = rootEditPart.m_aChildren;

    var textModels = [];
    $.each(models, function (index, model) {
      // console.log(model);
      // let canvas = model.figure.canvas;
      // canvas.setZoom(window.zoom, true);
      // 处理active未被定义的情况
      if (model.model.property.active === undefined) {
        model.model.property.active = false;
      }

      var typeName = model.model.property.modelProperty.typeName;
      if (
        typeName.indexOf("TextModelJson") != -1 ||
        typeName.indexOf("TextModelOval") != -1 ||
        typeName.indexOf("TextModelDiamond") != -1
      ) {
        textModels.push(model);
      }
      // 如果在实验台上找到了相应的流程框，则将active已为true的失活，且将找到的流程框激活
      var id = model.model.property.modelProperty.id;
      if (id == node.id) {
        rootEditPart.getFigure().setCurrentSelection(null);
        // model.model.property.active = true;
        model.getFigure().select(true);
        model.active();
      }
    });
    //对应的文本框
    var selectedModel = null;
    var notSelectedModel = [];
    $.each(textModels, function (index, model) {
      var id = model.model.property.modelProperty.id;
      if (id == node.id) {
        selectedModel = model;
      } else {
        notSelectedModel.push(model);
      }
    });
    if (selectedModel) {
      // $.outer.setDefaultZoom(); //设置默认的缩放比
      // selectedModel.model.property.active = true;
      // selectedModel.active();
      //改变背景图片
      // selectedModel.figure.bgColor.hashString = "#0F1A21";
      // selectedModel.figure.repaint();
      var modelX = selectedModel.model.property.uiProperty.x;
      var modelY = selectedModel.model.property.uiProperty.y;
      var context = app.components.APP_VIEW_COMPONENT_CANVAS.draw2dEditor.context;

      // let canvasDom = document.getElementById("app-canvas");
      // var zoom = context.getRootFigure().getZoom();
      let experimentDataJson = experimentData["firstPage"].json || experimentData["firstPage"];
      var zoom = experimentDataJson.experimentInfo.zoom;

      // let zoom1 = app.getContext().getActiveEditor().canvas.getZoom();
      // console.log(zoom1);

      console.log("[ zoom ] >", zoom);
      var scrollX = ((modelX / canvasWidth) * (canvasWidth - window.innerWidth)) / zoom;
      var scrollY = ((modelY / canvasHeight) * (canvasHeight - window.innerHeight)) / zoom;
      // 视野跳转;
      window.scrollTo(scrollX, scrollY);

      // if (notSelectedModel.length > 0) {
      //   $.each(notSelectedModel, function (index, model) {
      //     var bgColor = model.figure.properties.uiProperty.bgColor;
      //     model.figure.bgColor.hashString = bgColor;
      //     model.figure.repaint();
      //   });
      // }
    }
    // $.loading.close();
  },
  showDrawerPage() {
    layer.open({
      type: 1,
      // r表示right,b表示bottom
      offset: "rt",
      // 标题
      title: "属性栏",
      shadeClose: true, // 点击遮罩区域，关闭弹层
      // anim 特效 0-平滑放大 1-从上掉落 2-从底部往上滑入 3-从左滑入 4-从左翻转 5-渐显 6-抖动
      anim: 0,
      // 第一个参数宽度，第二个参数高度
      area: ["40%", "100%"],
      // 内容区 在body中写入<div id="draw">。。。。</div>代码，即弹窗内容
      content: $("#drawer-content"),
    });
  },
  //基础信息内容
  baseInfoCon() {
    this.initBaseInfoTableData();
    this.table.render({
      elem: "#base-table",
      cols: [this.baseInfo.tableCol],
      data: this.baseInfo.tableData,
      //skin: 'line', // 表格风格
      //even: true,
    });
    this.table.on("row(base-table)", ({ data }) => {
      $(".row-info-textarea").val(data.caption);
    });
  },
  //模型信息内容
  modelInfoCon() {
    this.initModelInfoTableData();
    this.table.render({
      elem: "#model-table",
      cols: [this.modelInfo.tableCol],
      data: this.modelInfo.tableData,
      //skin: 'line', // 表格风格
      //even: true,
    });
    this.table.on("row(model-table)", ({ data }) => {
      console.log("data.caption", data.caption);
      $(".row-info-textarea").val(data.caption);
    });
  },
  //基本信息和模型信息
  showPropDia(type) {
    var contentDom = `
      <div class="prop-con">
        <table class="layui-hide" id="${type}-table"></table>
        <div class="layui-form">
          <textarea name="" readonly placeholder="表格行的介绍" class="row-info-textarea layui-textarea"></textarea>
          <textarea name="" readonly placeholder="器材信息" class="partlib-info-textarea layui-textarea"></textarea>
        </div>
      </div>
    `;
    layer.open({
      type: 1, // page 层类型
      skin: "layui-layer-molv",
      area: ["80%", "80%"],
      title: type == "base" ? "基本属性" : "模型属性",
      shade: 0.6, // 遮罩透明度
      shadeClose: true, // 点击遮罩区域，关闭弹层
      // maxmin: true, // 允许全屏最小化
      anim: 0, // 0-6 的动画形式，-1 不开启
      content: contentDom,
    });
    //渲染弹框内容
    type == "base" ? this.baseInfoCon() : this.modelInfoCon();
  },
  /**
   * 函数功能：初始化选中元件的默认值<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  initBaseInfoTableData: function () {
    this.baseInfo.tableData = [];
    var modelProperty = this.getModelProp();
    console.log("modelProperty", modelProperty);
    var showInfo = modelProperty.showInfo; //属性对象的showInfo字段
    var partlibInfo = `${modelProperty.componentName}": "${modelProperty.partInfo}`;
    $(".partlib-info-textarea").val(partlibInfo);
    //填充基本信息表格
    if (showInfo) {
      //器件标签属性数据表行
      if (showInfo.showLabel) {
        var obj = {
          name: this.BASE_GRID_ROW_NAME_0,
          value: modelProperty.label.replace(/-/g, "."),
          visiable: showInfo?.showLabel?.visiable ? "Y" : "N",
          caption: "修改器件的标签或选择标签是否在实验台上显示",
        };
        this.baseInfo.tableData.push(obj);
      }

      if (showInfo.showComponentName) {
        //器件名称属性数据表行
        var obj = {
          name: this.BASE_GRID_ROW_NAME_1,
          value: modelProperty.componentName,
          visiable: showInfo?.showComponentName?.visiable ? "Y" : "N",
          caption: "修改器件的名称或选择器件的名称是否在实验台上显示",
        };
        this.baseInfo.tableData.push(obj);
      }

      if (showInfo.showEngName) {
        //器件名称属性数据表行
        var obj = {
          name: this.BASE_GRID_ROW_NAME_2,
          value: modelProperty.engName,
          visiable: showInfo?.showEngName?.visiable ? "Y" : "N",
          caption: "修改器件的英文名称",
        };
        this.baseInfo.tableData.push(obj);
      }

      //器件引脚标号属性数据表行
      if (showInfo.showPinNumber && showInfo.showPinNumber.showable) {
        var obj = {
          name: this.BASE_GRID_ROW_NAME_2,
          value: null,
          visiable: showInfo?.showPinNumber?.visiable ? "Y" : "N",
          caption: "选择器件引脚的标号是否在实验台上显示",
        };
        this.baseInfo.tableData.push(obj);
      }

      //器件引脚名称属性数据表行
      if (showInfo.showPinSymbol && showInfo.showPinSymbol.showable) {
        var obj = {
          name: this.BASE_GRID_ROW_NAME_3,
          value: null,
          visiable: showInfo?.showPinSymbol?.visiable ? "Y" : "N",
          caption: "选择器件引脚的名称是否在实验台上显示",
        };
        this.baseInfo.tableData.push(obj);
      }
    }
  },
  initModelInfoTableData: function (modelProperty) {
    this.modelInfo.tableData = [];
    var modelProperty = this.getModelProp();
    console.log("modelProperty", modelProperty);
    var partlibInfo = `${modelProperty.componentName}": "${modelProperty.partInfo}`;
    $(".partlib-info-textarea").val(partlibInfo);

    //处理spice属性列表
    if (modelProperty.additional.spiceProperties) {
      var modelProperties = modelProperty.additional.spiceProperties;
      console.log("[modelProperties  ] >", modelProperties);
      // var paraRegexp      = '';
      $.each(modelProperties, (i, para) => {
        var obj = {
          name: para.name,
          value: para?.value?.value || "",
          unit: para?.unit?.unitType || "",
          memo: para?.memo,
          unitOrders: para?.unit?.unitOrders || "",
          visiable: para.showInfo?.visiable ? "Y" : "N",
          showable: para.showInfo?.showable || false,
          editable: para.editable,
          caption: para.caption,
        };
        if (obj.name || obj.value || obj.unit || obj.memo) {
          this.modelInfo.tableData.push(obj);
        }
      });
    }
  },
  clear() {
    $("#drawer-content li").each(function () {
      $(this).removeClass("layui-menu-item-checked");
    });
    $("#tree-view").css({ display: "none" });
  },
});
